//reducer中发出登录请求
import {createSlice, createAsyncThunk, AsyncThunk} from "@reduxjs/toolkit";
import {RootState} from "../store";  //getState的返回类型
import {reqLogin} from "../../api/user/index";    //发送请求的api


// {
//     data:{
//         code : 0,
//         msg : "xxxx",
//         data : {
//              token,
//              id,
//              username,
//              avatar
//         }
//     }
// }

const initialState = {
    id : -1,
    username : "",
    avatar : "",
    token : localStorage.getItem("token") || "",
}


let userSlice = createSlice({
    name : "user",
    initialState,
    reducers : {
        // loginAsync : function(state,action:{type,payload}){//user/loginAsync
        //
        // }
    },
    extraReducers : (builder)=>{
        builder
            .addCase(loginAsync.fulfilled,(state, action)=>{
                // console.log("<<<<<",action.payload)
                if(action.payload){
                    let token = action.payload.token;
                    // console.log(">>>",action.payload);

                    state.token = token;  //token的更新,rtk当中的token更新了
                    //localStorage中也要更新
                    localStorage.setItem("token",token);
                }
            })
    }
})

export interface LoginParams{
    username : string,
    password : string
}
export const loginAsync = createAsyncThunk("user/loginAsync",({username,password}:LoginParams)=>{
    return reqLogin(username,password)
});

export const selectLang = (state : RootState) => state.user;

export default userSlice.reducer;